import gcoord from "../../miniprogram_npm/gcoord/dist/gcoord";
import moreConditions from "./condtion";
Page({
  data: {
    // 当前的位置
    latitude: "",
    longitude: "",
    // 画圆
    circles: [],
    nearByList: [], // 企业后台接口信息集合
    originList: [], // 原始列表数据
    markers: [], // 企业标记点集合
    data: [],
    markerId: "",
    activeIndex: 0, // 默认的产业选择
    actionType: 1, // 默认收缩
    pageNum: 1,
    total: "", // 附近企业总数
    titleName: "", // 页面的标题
    qiyeKey: {
      大型企业: "bigCorp",
      小微企业: "smallAndMicroCorp",
      无贷企业: "isLoan",
      外贸企业: "isTrade",
      瞪羚企业: "isGoats",
      政府采购: "isGovpur",
      高新技术: "isHightech",
      科技型中小企业: "technology",
      纳税A级: "taxALeavel",
      用工增长: "laborTrend",
      // 用电增长: "electricTrend",
      个体工商户: "electricTrend",
      '营收排名30%': "revenueLevel",
      '纳税排名30%': "taxLevel"
    },
    // 搜索筛选
    serach_pro: "",
    value1: "0.5",
    option1: [
      {
        text: "默认距离",
        value: "0.5",
      },
      {
        text: "1公里以内",
        value: "1.0",
      },
      {
        text: "2公里以内",
        value: "2.0",
      },
    ],
    value2: "",
    option2: [
      {
        text: "不限评分",
        value: "",
      },
      {
        text: "500分以下",
        value: "0-500",
      },
      {
        text: "500 - 599 分",
        value: "500-599",
      },
      {
        text: " 600 - 699 分",
        value: "600-699",
      },
      {
        text: "700 分以上",
        value: "700-10000",
      },
    ],
    // 更多
    option3: [],
    value3: "1",
    moreConditions: [],
    distance: "1.0", // 选择的距离
    scoreLowerLimit: "", // 选择的评分下限
    scoreUpperLimit: "", // 选择的评分上限
    showSelect: false,
    sortList: [
      {
        sortColumn: 'distance',
        sortRule: 'asc',
        label: '距离由近及远'
      },
      {
        sortColumn: 'distance',
        sortRule: 'desc',
        label: '距离由远及近'
      },
      {
        sortColumn: 'creditScore',
        sortRule: 'desc',
        label: '评分从高到低'
      },
      {
        sortColumn: 'creditScore',
        sortRule: 'asc',
        label: '评分从低到高'
      },
      {
        sortColumn: 'esdate',
        sortRule: 'asc',
        label: '成立日期由远及近'
      },
      {
        sortColumn: 'esdate',
        sortRule: 'desc',
        label: '成立日期由近及远'
      },
    ],
    activeIndex: 0,
    sortColumn: 'distance',
    sortRule: 'asc'
  },

  // 页面解析完成后执行
  onReady: function () {
    // 步骤一、常见地图实例对象
    this.mapCtx = wx.createMapContext("myMap");
  },
  onLoad: function (e) {
    this.setData({
      moreConditions: moreConditions.arr,
    });
    const that = this;

    // 设置页面的标题
    that.setData({
      titleName: e.titleName,
    });
    wx.setNavigationBarTitle({
      title: this.data.titleName, //页面标题为路由参数
    });
    // 获取当前的位置信息
    // getApp().globalData.getLocation({
    //   type: "gcj02",
    //   success(res) {
    that.initInfoByCenter(e);
    // },
    // });
    // this.initInfos();
  },

  /**
   * methods
   */
  initInfoByCenter (res) {
    //console.log(res)
    this.setData({
      longitude: this.transMarker([res.longitude, res.latitude])[0],
      latitude: this.transMarker([res.latitude, res.latitude])[1],
    });
    // center info
    this.setData({
      circles: [
        {
          latitude: res.latitude,
          longitude: res.longitude,
          color: "#7cb5ec88",
          opacity: 0.2,
          fillColor: "#7cb5ec88",
          radius: 600,
          strokeWidth: 2,
        },
      ],
    });

    // 数据初始化
    this.initInfos(res);
  },
  // 排序
  goSort () {
    this.setData({
      showSelect: true
    })
  },
  onClose () {
    this.setData({
      showSelect: false,
    });
  },
  selectOne (e) {
    const index = e.currentTarget.dataset.index
    const sortColumn = e.currentTarget.dataset.sortcolumn
    const sortRule = e.currentTarget.dataset.sortrule
    this.setData({
      activeIndex: index,
      sortColumn: sortColumn,
      sortRule: sortRule,
      showSelect: false,
    })
    this.clickCy();
  },
  // 初始化数据
  async initInfos (res) {
    // 获取周边企业的坐标
    await this.getNearByInfos(res);
    // 初始化markers
    this.initMarkers();
  },
  // 搜索企业
  serachProChange (e) {
    // this.close()
    this.setData({
      serach_pro: e.detail,
    });
    if (e.detail && e.detail.length > 3) {
      var setinval = null;
      if (setinval) {
        clearTimeout(setinval);
        setinval = null;
      } else {
        setinval = setTimeout(() => {
          this.clickCy();
          // this.originList
        }, 1000);
      }
    } else if (e.detail) {
      // this.setData({
      //   serach_pro: "",
      //   prolist: []
      // })
      // Toast("！")
    } else {
      this.setData({
        serach_pro: "",
        prolist: [],
      });
      this.getNearByInfos();
    }
  },
  inputFocus () {
    this.close();
  },
  inputBlur () {
    this.open();
  },
  // 筛选框打开
  selectOpen () {
    this.close();
  },
  selectClose () {
    this.open();
  },
  // 筛选距离
  distanceSelect (e) {
    // console.log(e);
    // console.log(this.data.value1);
    this.setData({
      distance: e.detail,
    });
    this.clickCy();
    this.open();
  },
  // 筛选评分
  scoreSelect (e) {
    console.log(e.detail);
    this.setData({
      value2: e.detail,
    });
    // scoreLowerLimit 下限
    // scoreUpperLimit 上限
    if (e.detail) {
      this.setData({
        scoreLowerLimit: e.detail.split("-")[0],
        scoreUpperLimit: e.detail.split("-")[1],
      });
    } else {
      this.setData({
        scoreLowerLimit: "",
        scoreUpperLimit: "",
      });
    }
    this.clickCy();
    this.open();
  },
  // 筛选更多
  setName (e) {
    console.log(e);
    // e.currentTarget.dataset.itempre.value = e.currentTarget.dataset.itemped.key;
    this.data.moreConditions.forEach((item, index) => {
      if (item.key == e.currentTarget.dataset.itemkey) {
        item.children.forEach((jtem) => {
          if (jtem.key == e.currentTarget.dataset.itempre.key) {
            jtem.value = e.currentTarget.dataset.itemped.key;
          }
        });
      }
    });
    this.setData({
      moreConditions: this.data.moreConditions,
    });
  },
  // 重置
  merescreenReset () {
    this.data.moreConditions.forEach((i) => {
      i.children.forEach((j) => {
        j.value = "";
      });
    });
    this.setData({
      moreConditions: this.data.moreConditions,
    });
  },
  // 确定选
  merescreenConfirm () {
    var allConditions = {};
    this.data.moreConditions.forEach((i) => {
      i.children.forEach((j) => {
        allConditions[j.key] = j.value;
      });
    });
    if (allConditions.numberOfCompanyUpperLimit) {
      allConditions.numberOfCompanyLowerLimit =
        allConditions.numberOfCompanyUpperLimit.split("_")[0];
      allConditions.numberOfCompanyUpperLimit =
        allConditions.numberOfCompanyUpperLimit.split("_")[1];
    }
    if (allConditions.registeredCapitalUpperLimit) {
      allConditions.registeredCapitalLowerLimit =
        allConditions.registeredCapitalUpperLimit.split("_")[0];
      allConditions.registeredCapitalUpperLimit =
        allConditions.registeredCapitalUpperLimit.split("_")[1];
    }
    if (allConditions.yearsOfEstablishUpperLimit) {
      allConditions.yearsOfEstablishLowerLimit =
        allConditions.yearsOfEstablishUpperLimit.split("_")[0];
      allConditions.yearsOfEstablishUpperLimit =
        allConditions.yearsOfEstablishUpperLimit.split("_")[1];
    }
    if (allConditions.businessIncomeLowerLimit) {
      allConditions.businessIncomeUpperLimit =
        allConditions.businessIncomeLowerLimit.split("_")[1];
      allConditions.businessIncomeLowerLimit =
        allConditions.businessIncomeLowerLimit.split("_")[0];
    }
    console.log(allConditions);
    this.setData({
      allConditions: allConditions,
    });
    this.clickCy();
    this.selectComponent("#dowente2").toggle(false);
    this.open();
  },
  // 获取附近企业的坐标
  async getNearByInfos () {
    const params = {
      userLng: this.data.longitude,
      userLat: this.data.latitude,
      pageBO: {
        pageSize: 10,
        pageNum: this.data.pageNum,
      },
      distance: this.data.distance,
      enterpriseName: this.data.serach_pro,
      sortColumn: this.data.sortColumn,
      sortRule: this.data.sortRule
    };
    switch (this.data.qiyeKey[this.data.titleName]) {
      case 'bigCorp':
        params[this.data.qiyeKey[this.data.titleName]] = '1'
        break;
      case 'smallAndMicroCorp':
        params[this.data.qiyeKey[this.data.titleName]] = '1'
        break;
      case 'isLoan':
        params[this.data.qiyeKey[this.data.titleName]] = '0'
        break;
      case 'isTrade':
        params[this.data.qiyeKey[this.data.titleName]] = '1'
        break;
      case 'isGoats':
        params[this.data.qiyeKey[this.data.titleName]] = '1'
        break;
      case 'isGovpur':
        params[this.data.qiyeKey[this.data.titleName]] = '1'
        break;
      case 'isHightech':
        params[this.data.qiyeKey[this.data.titleName]] = '1'
        break;
      case 'technology':
        params[this.data.qiyeKey[this.data.titleName]] = '1'
        break;
      case 'taxALeavel':
        params[this.data.qiyeKey[this.data.titleName]] = '1'
        break;
      case 'laborTrend':
        params[this.data.qiyeKey[this.data.titleName]] = '1'
        break;
      case 'electricTrend':
        params[this.data.qiyeKey[this.data.titleName]] = '1'
        break;
      case 'revenueLevel':
        params[this.data.qiyeKey[this.data.titleName]] = '30'
        break;
      case 'taxLevel':
        params[this.data.qiyeKey[this.data.titleName]] = '30'
        break;
      default:
        break;
    }

    console.log(params, "附近企业查询条件");
    var condtion = Object.assign(params, this.data.allConditions);
    wx.showLoading({
      title: "加载中",
    });
    const { list, total } = await getApp().globalData.request(
      "/map/lookAroundV2",
      condtion,
      "POST"
    );
    wx.hideLoading();
    console.log(list);
    // 原始列表数据
    this.setData({
      originList: this.data.originList.concat(list),
      total: total,
    });
    // 处理数据
    const resInfos = this.findSameList(this.data.originList);
    this.setData({
      nearByList: resInfos,
    });
    // console.log(this.data.originList, "原始附近企业查询结果");
    // console.log(this.data.nearByList, "附近企业查询结果");
  },

  // 初始化点标记
  initMarkers () {
    const markers = [];
    this.data.nearByList.forEach((val, index) => {
      const zuobiao = this.transMarker1([val[0].longitude, val[0].latitude]);
      // console.log(Math.floor((Math.random() * index)) * 0.0000001)
      val[0].longitude = zuobiao[0];
      val[0].latitude = zuobiao[1];
      markers.push({
        id: index,
        latitude: val[0].latitude,
        longitude: val[0].longitude,
        name: val[0].d2CorpName,
        corpKey: val[0].corpKey,
        iconPath:
          "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/zhoubian1.png",
        desc: "我现在的位置",
        title: val[0].d2CorpName,
        width: 14,
        height: 21,
        callout: {
          content: `${val[0].d2CorpName}${val.length > 0 ? "等" + val.length + "家企业" : ""
            },点击查看`,
          color: "#ffffff",
          bgColor: "#505d58", //需要6位的色值有效
          fontSize: 14,
          borderRadius: 2,
          padding: 5,
          display: "BYCLICK", //'BYCLICK':点击显示; 'ALWAYS':常显
        },
      });
    });
    // 中心点自定义样式
    // markers.push({
    //   id: 9999,
    //   latitude: this.data.circles[0].latitude,
    //   longitude: this.data.circles[0].longitude,
    //   name: "",
    //   iconPath:
    //     " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/center-location2.png",
    //   desc: "我现在的位置",
    //   title: "",
    //   width: 23,
    //   height: 31,
    // });
    this.setData({
      markers: markers,
    });
    // console.log(markers, "markers");
  },

  // 打开模糊地址搜索
  openSearch () {
    const that = this;
    wx.chooseLocation({
      success (res) {
        that.setData({
          // zb: JSON.stringify({
          //   longitude: res.longitude,
          //   latitude: res.latitude,
          // }),
        });
        console.log(res, "返回的结果");
        // 重新定位中心点，分页参数重置
        that.setData({
          pageNum: 1,
        });
        that.initInfoByCenter(res);
        // that.initInfoByCenter({ longitude: 120.642391, latitude: 31.369189 });
        console.log(res, "成功回调");
      },
      fail (res) {
        console.log(res, "失败回调");
      },
      complete (res) {
        console.log(res, "结束回调");
      },
    });
  },

  // 坐标系转化
  transMarker (item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.GCJ02, // 当前坐标系
      gcoord.BD09 // 目标坐标系
    );
    return resae;
  },

  // 中心点坐标转化
  transMarker1 (item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.BD09, // 当前坐标系
      gcoord.GCJ02 // 目标坐标系
    );
    return resae;
  },

  // 查找重复的数据,并且重新排列
  findSameList (item) {
    const needList = JSON.parse(JSON.stringify(item));
    // console.log(needList, 'needList')
    // 先去重复
    const singleList = this.removeDuplicateObj(needList);
    // console.log(singleList, 'singleList')
    const showList = [];
    singleList.forEach((val, index) => {
      const itemList = [];
      needList.forEach((pre) => {
        if (val.latitude === pre.latitude) {
          itemList.push(pre);
        }
      });
      showList.push(itemList);
    });
    // console.log(showList, "showList");
    return showList;
  },

  removeDuplicateObj (arr) {
    let obj = {};
    arr = arr.reduce((newArr, next) => {
      obj[next.latitude] ? "" : (obj[next.latitude] = 1 && newArr.push(next));
      return newArr;
    }, []);
    return arr;
  },

  // 跳转企业详情或者企业列表
  markerCalloutTap (e) {
    console.log(e.markerId, "e");
    if (this.data.nearByList[e.markerId].length > 1) {
      // 跳转到列表页面
      wx.navigateTo({
        url: `../../packageB/pages/businesses/businesses?businesses=${JSON.stringify(
          this.data.nearByList[e.markerId]
        )}`,
      });
    } else {
      // 跳转到详情页面
      wx.navigateTo({
        url: `../Company/Company?corpKey=${this.data.nearByList[e.markerId][0].corpKey
          }`,
      });
    }
  },

  // 扩展
  open () {
    this.setData({
      actionType: 1,
    });
  },

  // 收缩
  close () {
    this.setData({
      actionType: 0,
    });
  },

  toprodetail (e) {
    console.log(e.currentTarget.dataset.proitem.corpKey);
    // wx.setStorage({
    //   key: "Company",
    //   data: e.currentTarget.dataset.proitem
    // })
    wx.navigateTo({
      url:
        "/pages/Company/Company?corpKey=" +
        e.currentTarget.dataset.proitem.corpKey,
    });
  },
  // 滑动底部加载更多
  scrollBottom () {
    // this.onBottom();
    this.setData({
      pageNum: ++this.data.pageNum,
    });
    this.initInfos();
  },

  // 产业切换
  clickCy (e) {
    // 切换后重置分页参数和列表原始数组
    this.setData({
      pageNum: 1,
      originList: [],
    });
    this.initInfos();
  },

  // 返回到当前定位视窗
  locationBack () {
    this.mapCtx.moveToLocation();
  },
  toprodetail (e) {
    wx.navigateTo({
      url: `/pages/mapDetail/mapDetail?corpKey=${e.detail.corpKey}&latitude=${e.detail.latitude}&longitude=${e.detail.longitude}&distance=${e.detail.distance}`,
    });
  },
});
